import { create } from "zustand";
import { persist } from "zustand/middleware";

import { UserDataType } from "@/types/user";

// 初始状态
const initialState = {
  currentUserDetail: null as UserDataType | null,
};

// 状态类型
type UserManagerState = typeof initialState;

// Actions 类型
type UserManagerActions = {
  setCurrentUserDetail: (user: UserDataType | null) => void;
  clearCurrentUserDetail: () => void;
  updateCurrentUserDetail: (user: Partial<UserDataType>) => void;
};

// 合并状态和 Actions
type UserManagerStore = UserManagerState & UserManagerActions;

// 创建 store
export const useUserManagerStore = create<UserManagerStore>()(
  persist(
    (set) => ({
      ...initialState,

      setCurrentUserDetail: (user) => set({ currentUserDetail: user }),

      clearCurrentUserDetail: () => set({ currentUserDetail: null }),

      updateCurrentUserDetail: (user) =>
        set((state) => ({
          currentUserDetail: state.currentUserDetail ? { ...state.currentUserDetail, ...user } : null,
        })),
    }),
    { name: "app-user-manager" },
  ),
);

export const setCurrentUserDetail = (user: UserDataType | null) => {
  useUserManagerStore.getState().setCurrentUserDetail(user);
};

export const clearCurrentUserDetail = () => {
  useUserManagerStore.getState().clearCurrentUserDetail();
};

export const updateCurrentUserDetail = (user: Partial<UserDataType>) => {
  useUserManagerStore.getState().updateCurrentUserDetail(user);
};

export const getCurrentUserDetail = () => {
  return useUserManagerStore.getState().currentUserDetail;
};
